{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-default > .panel-heading .upload {
            overflow: hidden;
            float: right;
        }

        .panel-default > .panel-heading .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload-progress .progress-error {
            color: red;
        }

    </style>
{% endblock %}
{% block cotent %}
    <div class="container-fluid">
        <div class="panel panel-default">
            <div class="panel-heading clearfix" style="margin-top: auto"><i class="fa fa-book" aria-hidden="true"></i>
                <a href="{% url 'file' project_id=request.manage.id %}"> 文件管理 </a>
                {% for item in path_list %}
                    <span> 》 <a
                            href="{% url 'file' project_id=request.manage.id %}?file_id={{ item.id }}">{{ item.name }} </a> </span>
                {% endfor %}

                <span><button data-toggle="modal" data-target="#myModal" id="btn_create" style="float: right"
                              type="button" class="btn btn-sm btn-success" data-whatever="创建文件夹"
                >创建文件夹</button></span>
                <input style="float:right;margin-right: 5px" id="get_btn" type="button" class="btn btn-sm btn-primary"
                       value="获取token">
                <div class="btn btn-primary btn-sm upload" style="position: relative;margin-right: 5px">
                    <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                    <input type="file" multiple name="uploadFile" id="uploadFile">
                </div>
            </div>
            <div class="panel-body">
                <div class="bs-example" data-example-id="simple-table">
                    <table class="table">
                        <!-- <caption>Optional table caption.</caption> -->
                        <thead>
                        <tr>
                            <th>名称</th>
                            <th>大小</th>
                            <th>更新者</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for item in data_list %}
                            <tr>
                                {% if item.file_type == 1 %}
                                    <td>
                                        {{ item.name }}
                                    </td>
                                {% else %}
                                    <td>
                                        <a href="{% url 'file' project_id=request.manage.id %}?file_id={{ item.id }}">{{ item.name }}</a>
                                    </td>
                                {% endif %}
                                <td>
                                    {% if item.file_size %}
                                        {{ item.file_size }}
                                    {% else %}
                                        ....
                                    {% endif %}
                                </td>
                                <td>{{ item.update_user.username }}</td>
                                <td>{{ item.update_time }}</td>
                                <td>
                                    {% if item.file_type == 2 %}
                                        <a data-toggle="modal" data-target="#myModal" title="编辑" data-whatever="修改文件夹"
                                           id="edit-btn"
                                           name="{{ item.name }}" fid="{{ item.id }}"><i class="fa fa-edit"
                                                                                         aria-hidden="true"></i></a>
                                    {% else %}
                                        <a title="下载" id="down-btn"><i class="fa fa-cloud-download"
                                                                       aria-hidden="true"></i></a>
                                    {% endif %}
                                    <a id="dele-btn" data-toggle="modal" data-target="#deleModal"
                                       style="margin-left: 10px;" title="删除" fid="{{ item.id }}"><i
                                            class="fa fa-trash-o"
                                            style="color: red"></i></a>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel">New message</h4>
                </div>
                <form id="file_form" novalidate>
                    {% csrf_token %}
                    <div class="modal-body">
                        <input class="hide" type="text" name="fid" id="fid">
                        {% for itme in form %}
                            <div style="margin: 10px 0 20px 0">
                                <label style="margin-bottom: 10px;">{{ itme.label }}</label>
                                {{ itme }}
                                <span class="error" style="color: red;"> {{ itme.errors.0 }}</span>
                            </div>
                        {% endfor %}
                    </div>
                </form>
                <div class="modal-footer">
                    <button class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button id="save_btn" type="button" class="btn btn-primary">保 存</button>
                </div>

            </div>
        </div>
    </div>

    <div class="modal fade" id="deleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>是否要确定删除？</h4>
                <p style="padding-top: 20px;padding-bottom: 20px;">
                    文件夹中包含的所有的文件都会被删除。
                </p>
                <p style="text-align: right;">
                    <button type="button" class="btn btn-danger btn-sm" id="btn_delete">确 认</button>
                    <a class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                </p>
            </div>
        </div>
    </div>


{% endblock %}
{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var COS_CREDENTIAL = "{% url 'cors_token' project_id=request.manage.id %}";
        var FILE_POST = "{% url 'file' project_id=request.manage.id %}";
        var CURRENT_FOLDER_ID = "{{ folder_object.id }}";
        $(function () {
            get_token();
            bind_Uploadfile();
            init_modal();
            btn_sub();
            btn_dele();
        })

        function bind_Uploadfile() {
            $('#uploadFile').change(function () {
                //$('#progressList').empty();
                var fileList = $(this)[0].files;
                // 获取本次要上传的每个文件 名称&大小
                var checkFileList = [];
                $.each(fileList, function (index, fileObject) {
                    checkFileList.push({'name': fileObject.name, 'size': fileObject.size})
                });
                // 把这些数据发送到django后台：Django后台进行容量的校验，如果么有问题则返回临时凭证；否则返回错误信息；
                var cos_credential = new COS({
                    getAuthorization: function (options, callback) {
                        $.post(COS_CREDENTIAL, JSON.stringify(checkFileList), function (res) {
                            if (res.status) {
                                var credentials = res.data && res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    StartTime: res.data.startTime,
                                    ExpiredTime: res.data.expiredTime
                                });

                                $('#uploadProgress').removeClass('hide');
                            } else {
                                alert(res.error);
                            }
                        });
                    }
                });

                // 上传文件（上传之前先获取临时凭证
                $.each(fileList, function (index, fileObject) {
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key = (new Date()).getTime() + "_" + fileName;
                    var tr = $('#progressTemplate').find('tr').clone();
                    tr.find('.name').text(fileName);
                    $('#progressList').append(tr);

                    // 上传文件（异步）
                    cos_credential.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                        Region: '{{ request.tracer.project.region }}', /* 存储桶所在地域，必须字段 */
                        Key: key, /* 必须 */
                        Body: fileObject, // 上传文件对象
                        onProgress: function (progressData) {
                            var percent = progressData.percent * 100 + '%';
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                        }
                    }, function (err, data) {
                        if (data && data.statusCode === 200) {
                            // 上传成功，将本次上传的文件提交到后台并写入数据
                            // 当前文件上传成功
                            $.post(FILE_POST, {
                                name: fileName,
                                key: key,
                                file_size: fileSize,
                                parent: CURRENT_FOLDER_ID,
                                etag: data.ETag,
                                file_path: data.Location
                            }, function (res) {
                                // 在数据库中写入成功，将已添加的数据在页面上动态展示。
                                var newTr = $('#rowTpl').find('tr').clone();
                                newTr.find('.name').text(res.data.name);
                                newTr.find('.file_size').text(res.data.file_size);
                                newTr.find('.username').text(res.data.username);
                                newTr.find('.datetime').text(res.data.datetime);
                                newTr.find('.delete').attr('data-fid', res.data.id);
                                newTr.find('.download').attr('href', res.data.download_url);
                                $('#rowList').append(newTr);
                                // 自己的进度删除
                                tr.remove();
                            })

                        } else {
                            tr.find('.progress-error').text('上传失败');
                        }
                    });


                })
            });
        }

        function get_token() {
            $("#get_btn").click(function () {
                $.ajax({
                    url: "{% url 'cors_token' project_id=request.manage.id %}",
                    type: "POST",
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res)
                    }
                })
            })
        }

        function init_modal() {
            $('#myModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var recipient = button.data('whatever'); // Extract info from data-* attributes
                var name = button.attr("name") // Extract info from data-* attributes
                var fid = button.attr('fid'); // Extract info from data-* attributes
                var modal = $(this);
                modal.find('.modal-title').text(recipient);
                if (fid) {
                    modal.find('#id_name').val(name);
                    modal.find('#fid').val(fid);
                } else {
                    $('.error').empty();
                    $("#file_form")[0].reset();
                }
            })
            $('#deleModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var fid = button.attr('fid'); // Extract info from data-* attributes
                $("#btn_delete").attr("fid", fid);
            })
        };

        function btn_sub() {
            $("#save_btn").click(function () {
                $.ajax({
                    url: location.href,
                    data: $("#file_form").serialize(),
                    dataType: "JSON",
                    type: "post",
                    success: function (res) {
                        if (res.status) {
                            location.reload();
                        } else {
                            $.each(res.errors, function (name, msg) {
                                $("#id_" + name).next().text(msg)
                            })
                        }
                    }
                })
            })
        }

        function btn_dele() {
            $("#btn_delete").click(function () {
                $.ajax({
                    url: '{% url 'delete' project_id=request.manage.id %}',
                    data: {fid: $(this).attr("fid")},
                    type: "POST",
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            location.reload();
                        }
                    }
                })
            })
        }
    </script>
{% endblock %}
